﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using ProductManagement;
using Eb.StockManagement;

public partial class Modules_Purchase_ucAddProduct : System.Web.UI.UserControl
{
    StockManagement stockManagement = new StockManagement();
    Products _products = new Products();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            FillDDL();
            Session["Product_btnSaveSupplier"] = "false";
            if ((Session["Product_Add/EditProduct"].ToString() == "Edit") ||(Session["Product_Add/EditProduct"].ToString() == "Added"))
            {
                btnSave.Text = "Update";
                //if ((int)Session["Product_selectedProducts"] > 1)
                //{
                //    lbllTitle.Text = "ADD PRODUCT - ACCESSORY";
                //    btnSaveAccessory.Visible = true;
                //    for (int i = 2; i <= 15; i++)
                //        tblAddEditProduct.Rows[i].Visible = false;
                //}
                //else 
                //{
                    SearchAccessory();
                    SearchSupplier();
                //}
                btnAddAccessories.Enabled = true;
                btnAddAccessories0.Enabled = true;
                btnAddSupplier.Enabled = true;
                btnAddSupplier0.Enabled = true;
                LoadData();
                
            }
        }
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
          string[] ID = new string[1];
        
        if (Session["Product_Add/EditProduct"].ToString() == "Add")
        {
            Save();

                //Session["Product_IDs"] = _products.GetMaxProductID(); //get id of currently added product              
            ID[0] = _products.GetMaxProductID();//get id of currently added product   
            Session["Product_IDs"] = ID;
        }
        else if ((Session["Product_Add/EditProduct"].ToString() == "Edit") || (Session["Product_Add/EditProduct"].ToString() == "Added"))
        {            
            Update();            
            Back();
        }

        btnAddAccessories.Enabled = true;
        btnAddAccessories0.Enabled = true;
        btnAddSupplier.Enabled = true;
        btnAddSupplier0.Enabled = true;
    }

    void SearchAccessory()
    {
        try
        {
            DataSet dsAccessory;
            gvwAccessory.Visible = true;
            int count = (int)Session["Product_selectedProducts"];
            string toSearch = string.Empty;
            string productID = string.Empty;
            //if ((count == 1) && (Session["Product_btnAddAccessory"].ToString() == "false"))
            //    productID = ((string[])Session["Product_IDs"])[0].ToString();
            //if ((count == 1) && ((Session["Product_FromControl"].ToString() == "Production/ucProductList.ascx") || (Session["Product_FromControl"].ToString() == "Production/ucProductAccessory.ascx")))
                //if single product is selected or 
            productID = ((string[])Session["Product_IDs"])[0].ToString();           

            _products.SearchAccessory(productID, toSearch, out dsAccessory);
            gvwAccessory.DataSource = dsAccessory;
            gvwAccessory.Columns[0].Visible = true;
                      
            gvwAccessory.DataBind();
            //if (Session["Product_AddedAccessory"] == "false")
            //{
            //    gvwAccessory.Columns[0].Visible = false;
            //    gvwAccessory.Columns[7].Visible = true;
            //}
            //if (Session["Product_AddedAccessory"] == "true")
            //{
            //    gvwAccessory.Columns[0].Visible = true;
            //    gvwAccessory.Columns[7].Visible = false;
            //}
            gvwAccessory.Columns[0].Visible = false;                    
                    
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Search Accessories Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }

    }

    void SearchSupplier()
    {
        try
        {            
            //gvwVendors.Visible = true;
            //int count = (int)Session["Product_selectedProducts"];
            //string productID = string.Empty;
            //if ((count == 1) && ( Session["Product_btnAddSupplier"].ToString() == "false"))
            //    productID = ((string[])Session["Product_IDs"])[0].ToString();
            //DataSet dsVendor;
            //_products.SearchVendor(productID, "", out dsVendor);
            //gvwVendors.DataSource = dsVendor;
            //gvwVendors.Columns[0].Visible = true;
            //gvwVendors.Columns[1].Visible = true;

            //gvwVendors.DataBind();
            //if ( Session["Product_btnAddSupplier"] == "false")
            //{
            //    gvwVendors.Columns[0].Visible = false;
            //    gvwVendors.Columns[8].Visible = false;
            //    gvwVendors.Columns[9].Visible = true;
            //}
            //if (( Session["Product_btnAddSupplier"] == "true") || (count > 1))
            //{
            //    gvwVendors.Columns[0].Visible = true;
            //    gvwVendors.Columns[8].Visible = true;
            //    gvwVendors.Columns[9].Visible = false;
            //}
            //gvwVendors.Columns[1].Visible = false;

            DataSet dsVendor;
            gvwVendors.Visible = true;
            int count = (int)Session["Product_selectedProducts"];
            string toSearch = string.Empty;
            string productID = string.Empty;
            //if ((count == 1) && (Session["Product_btnAddAccessory"].ToString() == "false"))
            //    productID = ((string[])Session["Product_IDs"])[0].ToString();
            //if ((count == 1) && ((Session["Product_FromControl"].ToString() == "Production/ucProductList.ascx") || (Session["Product_FromControl"].ToString() == "Production/ucProductAccessory.ascx")))
            //if single product is selected or 
            productID = ((string[])Session["Product_IDs"])[0].ToString();

            _products.SearchVendor(productID, toSearch, out dsVendor);
            gvwVendors.DataSource = dsVendor;
            gvwVendors.Columns[0].Visible = true;

            gvwVendors.DataBind();
            gvwVendors.Columns[0].Visible = false;           

        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Search Suppliers Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }

    }

    void Save()
    {
        try
        {
            Product addProduct = new Product();              
                addProduct.ProductCode = txtProductCode.Text;
                addProduct.Name = txtName.Text;
                addProduct.Description = txtDescription.Text;
                addProduct.UPC = txtUPC.Text;
                addProduct.ListPrice = txtListPrice.Text;
                addProduct.Type =ddlType.SelectedItem.Value;
                addProduct.Stock = txtStock.Text;
                addProduct.Unit = txtUnit.Text;
                addProduct.Specification = txtSpecification.Text;

                if (_products.AddProduct(addProduct))
                {
                    int stock=0;
                    if(txtStock.Text.Trim()!="" || txtStock.Text!=null)
                    {
                      stock=Convert.ToInt16(txtStock.Text);

                    }
                    else
                    {
                        stock=0;
                    }
                    
                    int userId = 0;
                    if (Session["UserId"] != null)
                        userId = Convert.ToInt16(Session["UserId"].ToString());

                    int productId =Convert.ToInt32(_products.GetMaxProductID());
                    bool batchHistoryStatus= stockManagement.InsertBatchHistory(productId.ToString(), stock,1,"","",userId.ToString(),"","","");
                    bool productStockStatus= stockManagement.UpdateCurrentAvailabilityOfStock(productId,stock,txtUnit.Text);
                    Response.Write("<Script>alert('Added Successfully !')</Script>");
                    Session["Product_Add/EditProduct"] = "Added";
                    btnSave.Text = "Update";
                    //Clear();
                }
                else
                    Response.Write("<Script>alert('Already Exist !')</Script>");

        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Add Product Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }

    void LoadData()
    {
        try
        {
            string condition = "ProductID = '" + ((string[])Session["Product_IDs"])[0].ToString() + "'";
            DataSet dsProducts = _products.GetData("ProductList", condition);
            txtProductCode.Text = dsProducts.Tables[0].Rows[0]["ProductCode"].ToString();
            txtName.Text = dsProducts.Tables[0].Rows[0]["ProductName"].ToString();
            txtDescription.Text = dsProducts.Tables[0].Rows[0]["ProductDescription"].ToString();
            txtUPC.Text = dsProducts.Tables[0].Rows[0]["UPC"].ToString();
            txtListPrice.Text = dsProducts.Tables[0].Rows[0]["ListPrice"].ToString();
            txtStock.Text = dsProducts.Tables[0].Rows[0]["Stock"].ToString();
            txtUnit.Text = dsProducts.Tables[0].Rows[0]["Unit"].ToString();
            txtSpecification.Text = dsProducts.Tables[0].Rows[0]["Specification"].ToString();

        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Load Data Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }

    void Update()
    {
        int productID = 0;
        int stock = 0;
        int userId = 0;
        if (Session["UserId"] != null)
            userId = Convert.ToInt16(Session["UserId"].ToString());

        Product editProduct = new Product();

        editProduct.ID = ((string[])Session["Product_IDs"])[0].ToString();
        editProduct.ProductCode = txtProductCode.Text;
        editProduct.Name = txtName.Text;
        editProduct.Description = txtDescription.Text;
        editProduct.UPC = txtUPC.Text;
        editProduct.ListPrice = txtListPrice.Text;
        editProduct.Type = ddlType.SelectedItem.Value ;
        editProduct.Stock = txtStock.Text;
        editProduct.Unit = txtUnit.Text;
        editProduct.Specification = txtSpecification.Text;

        _products.EditProduct(editProduct);
        if (txtStock.Text.Trim() != "" || txtStock.Text.Trim()!=null)
        {
            stock = Convert.ToInt16(txtStock.Text.Trim());
        }
        else
        {
            stock = 0;
        }
        if(editProduct.ID!="" || editProduct.ID!=null)
        {
            productID = Convert.ToInt16(editProduct.ID);
        }
        bool batchHistoryStatus = stockManagement.InsertBatchHistory(editProduct.ID, stock, 1, "", "", userId.ToString(), "", "", "");
        bool productStockStatus = stockManagement.UpdateProductStock(productID, stock, txtUnit.Text);

    }

    void FillDDL()
    {
        DataSet dsProductType = _products.GetData("ProductType",string.Empty);
        ddlType.DataSource = dsProductType;
        ddlType.DataTextField = "TypeName";
        ddlType.DataValueField = "Type";
        ddlType.DataBind();
        ddlType.Items.Insert(0,"Select");
    }
    void Clear()
    {
        txtName.Text = string.Empty;
        txtProductCode.Text = string.Empty;
        txtDescription.Text = string.Empty;
        txtUPC.Text = string.Empty;
        ddlType.ClearSelection();
        txtListPrice.Text = string.Empty;
        txtStock.Text = string.Empty;
        txtUnit.Text = string.Empty;
        txtSpecification.Text = string.Empty;
    }

    void Back()
    {
        Session["UserManager_Control"] = "Production/ucProductList.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx");
    }

    void GetIDs()
    {
        try
        {
            int countAccessory = 0;
            int countSupplier = 0;
            string[] accessoryID = new string[gvwAccessory.Rows.Count];
            string[] supplierID = new string[gvwVendors.Rows.Count];
            string[] supplierPriority = new string[gvwVendors.Rows.Count];

            for (int i = 0; i < gvwAccessory.Rows.Count; i++)  //checking selected Accessories
            {
                accessoryID[i] = string.Empty;
                CheckBox chkGrid = (CheckBox)(gvwAccessory.Rows[i].Cells[0].FindControl("chkEditDelete"));
                if (chkGrid.Checked == true)
                {
                    accessoryID[countAccessory] = gvwAccessory.Rows[i].Cells[1].Text;
                    countAccessory++;
                }
            }

            if (Session["Product_btnSaveSupplier"] == "true") //validate gridvendors if save vendor is clicked
            {
                for (int j = 0; j < gvwVendors.Rows.Count; j++) //checking selected suppliers
                {
                    supplierID[j] = string.Empty;
                    CheckBox chkGrid = (CheckBox)(gvwVendors.Rows[j].Cells[0].FindControl("chkEditDelete"));
                    DropDownList ddlGrid = (DropDownList)(gvwVendors.Rows[j].Cells[8].FindControl("ddlRank"));
                    if ((chkGrid.Checked == true) && (ddlGrid.SelectedIndex == 0))
                    {
                        Response.Write("<script>alert('Select Priority')</script>");
                        Session["Product_validate"] = "failed";
                        return;
                    }
                    if ((chkGrid.Checked == true) && (ddlGrid.SelectedIndex != 0))
                    {
                        supplierID[countSupplier] = gvwVendors.Rows[j].Cells[1].Text;
                        supplierPriority[countSupplier] = ddlGrid.SelectedItem.ToString();
                        //Session["Purchase_Rank"] = ddlGrid.SelectedItem.ToString();
                        countSupplier++;
                    }

                    for (int k = j + 1; k < gvwVendors.Rows.Count; k++)
                    {
                        CheckBox chkGrid2 = (CheckBox)(gvwVendors.Rows[k].Cells[0].FindControl("chkEditDelete"));
                        DropDownList ddlGrid2 = (DropDownList)(gvwVendors.Rows[k].Cells[3].FindControl("ddlRank"));
                        if ((chkGrid2.Checked) && (ddlGrid.SelectedIndex != 0) && (ddlGrid.SelectedIndex == ddlGrid2.SelectedIndex))
                        {
                            Response.Write("<script>alert('Vendors Should Be Of Different Priority')</script>");
                            Session["Product_validate"] = "failed";
                            return;
                        }
                    }
                }
            }

            Session["Product_validate"] = "succeeded";
            Session["Product_AddSupplierIDs"] = supplierID;
            Session["Product_SupplierPriority"] = supplierPriority;
            Session["Product_selectedSuppliers"] = countSupplier;

            Session["Product_AddAccessoryIDs"] = accessoryID;
            Session["Product_selectedAccessories"] = countAccessory;
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Get ID Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
    }

  

    void AddAccessory()
    {
        try
        {
            int countAccessory = (int)Session["Product_selectedAccessories"];// no: of accessories selected(checked in the grid)           
            if (Session["Product_Add/EditProduct"] == "Add")  //if accessory is to be added to newly entered product
                Session["Product_selectedProducts"] = 1;
            int countProducts = (int)Session["Product_selectedProducts"];//no: of products selected

            string[] productIDs = (string[])Session["Product_IDs"];
            string[] accessoryIDs = (string[])Session["Product_AddAccessoryIDs"];

            for (int i = 0; i < countProducts; i++)
                for (int j = 0; j < countAccessory; j++)
                    _products.AddProductAccessory(productIDs[i], accessoryIDs[j]);
            
        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Add Product - Accessory Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }
        
    }

    void AddSupplier()
    {
        try
        {
            int countSupplier = (int)Session["Product_selectedSuppliers"]; // no: of suppliers selected(checked in the grid)            
            if (Session["Product_Add/EditProduct"] == "Add")  //if supplier is to be added to newly entered product
                Session["Product_selectedProducts"] = 1;
            int countProducts = (int)Session["Product_selectedProducts"]; // no: of products selected

            string[] productIDs = (string[])Session["Product_IDs"];
            string[] supplierIDs = (string[])Session["Product_AddSupplierIDs"];
            string[] Priority = (string[])Session["Product_SupplierPriority"];

            for (int i = 0; i < countProducts; i++)
                for (int j = 0; j < countSupplier; j++)
                    _products.AddProductSupplier(productIDs[i], supplierIDs[j], Priority[j]);

        }
        catch (Exception exp)
        {
            Session["ERRTITLE"] = "Add Product - Supplier Failed";
            Session["ERRDET"] = exp.Message;
            Response.Redirect("ErrorPage.aspx");
        }

    }

    protected void lnbBack_Click(object sender, EventArgs e)
    {
        Back();
    }
    protected void btnAddAccessories_Click(object sender, EventArgs e)
    {       
        AddAccessoryButtonClick();
    }
    protected void btnAddAccessories0_Click(object sender, EventArgs e)
    {
        AddAccessoryButtonClick();
    }

    protected void btnAddSupplier_Click(object sender, EventArgs e)
    {
        //tblAddEditProduct.Rows[13].Visible = true;
        //tblAddEditProduct.Rows[15].Visible = true;
        AddSupplierButtonClick();
    }
    protected void btnAddSupplier0_Click(object sender, EventArgs e)
    {
        AddSupplierButtonClick();
    }

    void AddAccessoryButtonClick()
    {
        Session["Product_FromControl"] = "Production/ucAddProduct.ascx";
        Session["Product_btnAddAccessory"] = "true";
        Session["UserManager_Control"] = "Production/ucProductAccessory.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx"); 
    }

    void AddSupplierButtonClick()
    {
        //string[] ID = new string[1];
        //if (Session["Product_Add/EditProduct"].ToString() == "Add")
        //{
        //    ID[0] = _products.GetMaxProductID();
        //    Session["Product_IDs"] = ID;
        //}
        //btnSave.Visible = false;
        //btnSaveAccessory.Visible = false;
        //btnSaveSupplier.Visible = true;
        //gvwAccessory.Visible = false;
        //Session["Product_btnAddSupplier"] = "true";
        ////Session["Product_selectedProducts"] = 0;
        //SearchSupplier();

        Session["Product_FromControl"] = "Production/ucAddProduct.ascx";
        Session["Product_btnAddSupplier"] = "true";
        Session["UserManager_Control"] = "Production/ucProductSupplier.ascx";
        Response.Redirect("BusinessProcessAutomation.aspx"); 
    }


    protected void gvwAccessory_RowCommand(object sender, GridViewCommandEventArgs e)
    {       
            int index = Convert.ToInt32(e.CommandArgument);
            // string productID = gvwAccessory.Rows[index].Cells[1].Text;
            string productID = ((string[])Session["Product_IDs"])[0].ToString();
            string accessoryID = gvwAccessory.Rows[index].Cells[0].Text;
            _products.DeleteProductAccessory(productID, accessoryID);
            SearchAccessory();
        
    }

    //void Delete()
    //{
    //    LinkButton lnbGridRoles = (LinkButton)sender;
    //    GridViewRow gvRow = (GridViewRow)lnbGridRoles.NamingContainer;
    //    string roleID = gvRow.Cells[1].Text;
    //}

    protected void gvwVendors_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        int index = Convert.ToInt32(e.CommandArgument);
        // string productID = gvwAccessory.Rows[index].Cells[1].Text;
        string productID = ((string[])Session["Product_IDs"])[0].ToString();
        string supplierID = gvwVendors.Rows[index].Cells[0].Text;
        _products.DeleteProductSupplier(productID, supplierID);
        SearchSupplier();
    }

    protected void btnSaveAccessory_Click(object sender, EventArgs e)
    {
        Session["Product_btnSaveSupplier"] = "false";
        GetIDs();
        AddAccessory();
        Session["Product_btnAddAccessory"] = "false";        
       

        if ((int)Session["Product_selectedProducts"] == 1)
        {
            SearchAccessory();
            btnSave.Visible = true;
        }
        else
        {
            gvwAccessory.Visible = false;
            tblAddEditProduct.Rows[15].Visible = false;
        }
        Response.Write("<script>alert('Accessories Added Successfully !')</script>");
    }

    
    protected void btnSaveSupplier_Click(object sender, EventArgs e)
    {
            Session["Product_btnSaveSupplier"] = "true";
            GetIDs();
            if (Session["Product_validate"] == "failed")
                return;
            AddSupplier();
            Session["Product_btnAddSupplier"] = "false";
          
            if ((int)Session["Product_selectedProducts"] == 1)
            {
                SearchSupplier();
                btnSave.Visible = true;
            }
            else
            {
                gvwVendors.Visible = false;
                tblAddEditProduct.Rows[15].Visible = false;
            }
            Response.Write("<script>alert('Suppliers Added Successfully !')</script>");        
    }

    protected void gvwVendors_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvwVendors.PageIndex = e.NewPageIndex;
        SearchSupplier();
    }
    protected void gvwVendors_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // if (e.Row.RowType == DataControlRowType.DataRow)
        //{
        //    DropDownList ddlGrid = (DropDownList)e.Row.FindControl("ddlRank");
           
        //    ddlGrid.Items.Insert(0, "Select");
        //    ddlGrid.Items.Add("1");
        //    ddlGrid.Items.Add("2");
        //    ddlGrid.Items.Add("3");            
           
        //}

        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";

        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";
    }



    protected void gvwAccessory_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {

            e.Row.Attributes.Add("onmouseover", "MouseEvents(this, event)");

            e.Row.Attributes.Add("onmouseout", "MouseEvents(this, event)");

        }
        if (e.Row.RowType == DataControlRowType.EmptyDataRow)
            e.Row.CssClass = "grid-view-header";

        if (e.Row.RowType == DataControlRowType.Header)
            e.Row.CssClass = "grid-view-header";

        //Add CSS class on normal row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Normal)
            e.Row.CssClass = "grid-view-normal";

        //Add CSS class on alternate row.
        if (e.Row.RowType == DataControlRowType.DataRow &&
                  e.Row.RowState == DataControlRowState.Alternate)
            e.Row.CssClass = "grid-view-alternate";
    }
    protected void gvwAccessory_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvwAccessory.PageIndex = e.NewPageIndex;
        SearchAccessory();
    }
    protected void btnClose_Click(object sender, EventArgs e)
    {
        Back();
    }
}
